<?php
	/**
	* Shopping Cart Final: checkout successfull
	* 
	* @author trungdt
	* @since Oct 19, 2011
	* 
	* Change logs
	* 
	*/

	if (!defined('EXPONENT')) exit('');
	if (!defined('SYS_USERS')) include_once(BASE.'subsystems/users.php');

	// if not logged, must redirect back to shopping cart view
	if (!exponent_users_isLoggedIn())
	{
		$params=array();
		$params['modules']="productsmodule";
		$params['action']="cart_view";
		$link=$router->makeLink($params);
		header("Location: {$link}");
		die(); 
	}

	if (!defined("ABProductsModule_Carts"))
		define("ABProductsModule_Carts","ABShopCart_SessionKey");

	$carts=exponent_sessions_get(ABProductsModule_Carts);
	if ($carts == null)
		$carts = array();

	if (count($carts) == 0 || !exponent_sessions_isset("AB_ProductsModule_ShoppingCart_ShipMethod"))
	{
		// redirect to homepage
		header("Location: /");
		die();
	}

	// create new bill
	$bill=productsmodule::__Bill_AddNew();

	// recalculate all products in shopping cart, for detail to send email
	$currency=null; // hhee, trick to save last config, for currency format to cart total
	$cart_count=0;
	$cart_total=0;
	foreach ($carts as $v)
	{
		$cart_count+=$v->quantity;
		// calculate total of this cart
		$temp=$v->quantity;
		if ($v->on_sale)
			$temp*=$v->price_sale_bk;
		else
			$temp*=$v->price_bk;
		$cart_total+=$temp;
		$v->price_total_value=$temp;
		$v->price_total=$temp;

		// add new products in bills_detail
		$temp=null;
		$temp->bill_id=$bill->id;
		$temp->product_id = $v->id;
		$temp->product_name = $v->title;
		$temp->product_sku = $v->sku;
		if ($v->on_sale)
            $temp->product_price=$v->price_sale_bk;
        else
            $temp->product_price=$v->price_bk;
		$temp->product_quantity = $v->quantity;
		$temp->product_price_orginal= $v->price_bk;
		// insert into db
		$db->insertObject($temp, "productsmodule_bills_details");
	}
	$cart_tax=0.1*$cart_total;
	$cart_total2 = $cart_tax + $cart_total;

	// for shipping 
	// we should determine what method will we use
	$shipping_method=exponent_sessions_get("AB_ProductsModule_ShoppingCart_ShipMethod");
	$shipping_registered=null;
	$shipping_manual=null;
	$shipping_info = productsmodule::__Get_User_Shipping($shipping_registered, $shipping_manual);

	// add info to bill
	$bill->buyer_user_id = $user->id;
	$bill->buyer_user_name = "{$user->firstname} {$user->lastname} ({$user->username})";
	$bill->bill_total= $cart_total2;
	$bill->bill_state = 0;
	$bill->buy_date = aboid_getCurrentTime();
	$bill->buyer_email = $user->email;
	$bill->included_tax = $cart_tax;
	$bill->included_shipping = 0;
	$bill->quantity_count = $cart_count;
	$bill->ip_address=  $_SERVER['REMOTE_ADDR'];
	// and update shipping info
	$bill->bk_id=$bill->id;
	foreach (get_object_vars($shipping_info) as $var=>$val) {
		if (strpos($var, "info")!==false)
            $bill->$var=$val;
	}
	$bill->id=$bill->bk_id;
	unset($bill->bk_id);

	$db->updateObject($bill, "productsmodule_bills");
	
	productsmodule::__Bill_AddLogs("Completed add new bill on ".date('F j, Y, H:i:s',aboid_getCurrentTime()).". Bill Code #{$bill->id}", $bill->id);
	
	// send email
	$lang=exponent_lang_loadFile("modules/productsmodule/actions/cart_final.php");
	$html=exponent_sessions_get("AB_ProductsModule_ShoppingCart_DetailHTML");
	
	// prepare for send mail to admin : render HTML
	$template=new template("productsmodule","_cart_final_forAdmin");
	$template->assign("html", $html);
    $template->assign("mode", 0);
	$template->assign("bill_id", $bill->id);
	$html_admin=$template->render();
	$template->assign("mode", 1);
	$html_customer=$template->render();
	
	$headers['From'] =  SMTP_FROMADDRESS ;
	$headers['Reply-to'] = SMTP_FROMADDRESS;
	require_once(BASE.'subsystems/mail.php');
	$mail = null;
	// build emails to send
	$emails=array();
	$temp=null;
	
	// send email to admin to let they know about this bill
	$temp->email=SMTP_FROMADDRESS;
	$temp->name=$lang['email_from_title'];
	$temp->subject=str_replace(array("%1", "%2"), array($user->username, date('F j, Y, H:i:s',aboid_getCurrentTime())." (GMT ".ABOID_NEEDED_BELT.")"), $lang['email_admin_title']);
	$temp->html=$html_admin;
	$emails[]=clone $temp;
	// send email to customer to confirm the bill
	$temp->email=$user->email;
	$temp->name=$lang['email_from_title'];
	$temp->subject=str_replace(array("%1"), array(date('l jS \of F Y H:i:s', aboid_getCurrentTime())), $lang['email_from_title_customer']);
	$temp->html=$html_customer;
	$emails[]=clone $temp;
	foreach ($emails as $email)
	{
		try
		{
			$mail = new exponentMail();
			$name = $email->name;

			$mail->addTo($email->email);
			$mail->subject($email->subject);
			$mail->addHTML($email->html);
			$mail->addHeaders($headers);
			$mail->addFrom(SMTP_FROMADDRESS, $email->name );

			try
			{
				// Send the message
				@$mail->send();
			}
			catch (Exception $e)
			{
				continue;
			}

		}
		catch (Exception $e)
		{
			productsmodule::__Bill_AddLogs("Send notification mail error". var_export($e), $bill->id);
		}
	}
	
	productsmodule::__Bill_AddLogs("Completed send notification email", $bill->id);
	exponent_theme_setFlagAjaxAction(true);
	
	// success, must clear all session carts
	exponent_sessions_unset(ABProductsModule_Carts);
	exponent_sessions_unset("AB_ProductsModule_ShoppingCart_ShipMethod");
	exponent_sessions_unset("AB_ProductsModule_ShoppingCart_DetailHTML");
	
	exponent_flow_redirect();
	//
?>
